package com.joplus.housekeeper.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hyphenate.chatuidemo.DemoApplication;
import com.joplus.housekeeper.R;
import com.joplus.housekeeper.base.BaseActivity;
import com.joplus.housekeeper.bean.ImageBean;
import com.joplus.housekeeper.bean.MessageAccountListBean;
import com.joplus.housekeeper.bean.User;
import com.joplus.housekeeper.bean.UserNew;
import com.joplus.housekeeper.bean.XmppUser;
import com.joplus.housekeeper.core.Config;
import com.joplus.housekeeper.network.RequestHelper;
import com.joplus.housekeeper.network.TextCallback;

import com.joplus.housekeeper.ui.fragment.xmppCustomer.LabelFragment;
import com.joplus.housekeeper.ui.fragment.xmppCustomer.OrderFragment;
import com.joplus.housekeeper.ui.fragment.xmppCustomer.PersonFragment;
import com.joplus.housekeeper.ui.view.timeSelector.TimeSelector;
import com.joplus.housekeeper.utils.Imageutils;
import com.joplus.housekeeper.utils.L;
import com.joplus.housekeeper.utils.RealmHelper;
import com.joplus.housekeeper.utils.SPUtils;
import com.joplus.housekeeper.utils.StringUtils;
import com.joplus.housekeeper.utils.SystemBarTintManager;
import com.joplus.housekeeper.utils.T;
import com.joplus.housekeeper.utils.UMengUtils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;

import de.hdodenhof.circleimageview.CircleImageView;
import io.realm.RealmResults;

/**
 * 个人资料
 * Created by bianxiang on 16/4/28.
 */
public class PersonDataActivity extends BaseActivity {
    private CircleImageView circleImageView;
    private TextView tvName, tvBirthday, tvPhone, tvEmail, tvAddress, tvSex;

    private TextView tv_banner_name;
    private RadioGroup rg;
    private String userId;
    private MessageAccountListBean user;

    @Override
    protected int initLayout() {
        return R.layout.activity_person_data;
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {


        init();

        circleImageView = (CircleImageView) findViewById(R.id.profile_image);
        tvName = (TextView) findViewById(R.id.tv_name);

        tv_banner_name = (TextView) findViewById(R.id.tv_banner_name);
        rg = (RadioGroup) findViewById(R.id.rg);

        if (savedInstanceState != null)
            tempFile = new File(savedInstanceState.getString("tempFile", ""));


        user = getIntent().getParcelableExtra("user");
        ImageLoader.getInstance().displayImage(user.getAvatar(), circleImageView);
    }

    @Override
    protected void initDatas() {
        initView();
    }


    Fragment[] fragments;
    int index = 0;

    public void calendar(View view) {
        Intent intent = new Intent(context, ChatCalendarActivity.class);
        intent.putExtra("accountId", user.getAccountId());
        startActivity(intent);
    }

    private String accountId;

    @Override
    protected void initEvents() {


        StringUtils.setText(tv_banner_name, user.getMobile());

        accountId = user.getAccountId();
        LabelFragment labelFragment = new LabelFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userId", userId);
        bundle.putString("accountId", accountId);
        labelFragment.setArguments(bundle);


        OrderFragment orderFragment = new OrderFragment();
        Bundle bundle1 = new Bundle();
        bundle1.putString("accountId", user.getAccountId());
        orderFragment.setArguments(bundle1);


        PersonFragment personFragment = new PersonFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putParcelable("user", user);

        personFragment.setArguments(bundle2);

        fragments = new Fragment[]{orderFragment, personFragment, labelFragment};
        getSupportFragmentManager().beginTransaction().add(R.id.fl_container, labelFragment).add(R.id.fl_container, orderFragment).hide(orderFragment).add(R.id.fl_container, personFragment).hide(personFragment)
                .commit();


        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                switch (checkedId) {
                    case R.id.rb_1:
                        if (index == 0) {
                            return;
                        }

                        fragmentTransaction.hide(fragments[index]);
                        if (!fragments[0].isAdded()) {
                            fragmentTransaction.add(R.id.fl_container, fragments[0]);
                        }
                        fragmentTransaction.show(fragments[0]).commit();
                        index = 0;
                        break;
                    case R.id.rb_2:
                        if (index == 1) {
                            return;
                        }
                        fragmentTransaction.hide(fragments[index]);
                        if (!fragments[1].isAdded()) {
                            fragmentTransaction.add(R.id.fl_container, fragments[1]);
                        }
                        fragmentTransaction.show(fragments[1]).commit();
                        index = 1;
                        break;
                    case R.id.rb_3:
                        if (index == 2) {
                            return;
                        }

                        fragmentTransaction.hide(fragments[index]);
                        if (!fragments[1].isAdded()) {
                            fragmentTransaction.add(R.id.fl_container, fragments[2]);
                        }
                        fragmentTransaction.show(fragments[2]).commit();
                        index = 2;
                        break;
                }
            }
        });
        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
             /*   AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("选择照片");
                builder.setItems(new String[]{"照片", "拍照"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                        switch (which) {
                            case 0:
                                gallery();
                                break;
                            case 1:
                                camera();
                                break;
                        }
                    }
                });
                builder.show();*/
            }
        });
    }

    @Override
    protected boolean isSlideFinishActivity() {
        return false;
    }

    @Override
    protected int setTranslucentStatusColor() {
        return -1;
    }


    private static final int PHOTO_REQUEST_GALLERY = 111;
    private static final int PHOTO_REQUEST_CAREMA = 112;
    private static final int PHOTO_REQUEST_CUT = 113;

    /*
     * 从相册获取
     */
    public void gallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    private File tempFile;

    /*
     * 从相机获取
     */
    public void camera() {
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    "win_label.png");

            if (tempFile.exists()) {
                tempFile.delete();
            }
            // 从文件中创建uri
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }


    public static boolean hasSdcard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);

    }

    /*
     * 剪切图片
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    private void upload(final Bitmap paramBitmap) {

      /*  circleImageView.setImageBitmap(paramBitmap);

        final File headFile = Imageutils.saveBitmap(paramBitmap);
        L.e("onActivityResult-->" + headFile);

        RequestHelper.getInstance().updateIcon(headFile, new TextCallback() {
            public void onFailure(String paramString) {
                L.e(this.getClass().getSimpleName() + "onFailure    " + paramString);

            }

            public void onSuccess(Object paramObject) {


                Gson gson = new Gson();
                ImageBean imageBean = gson.fromJson((String) paramObject, ImageBean.class);
                if (!imageBean.getCode().equals(getString(R.string.right_code))) {
                    return;
                }
                circleImageView.setImageBitmap(paramBitmap);
            }
        });*/
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
//                Uri uri = data.getData();
//                crop(uri);


                L.e("onActivityResult-->" + data.toString());
                Uri localUri = data.getData();
                String str = Imageutils.getRealFilePath(this.context, localUri);
                L.e("onActivityResult-->" + str);
                Bitmap localBitmap2 = Imageutils.decodeFile(str);
                int j = Imageutils.readPictureDegree(new File(str).getAbsolutePath());
                L.e("角度 : " + j);
                if (j != 0)
                    localBitmap2 = Imageutils.rotateBitmap(localBitmap2, 90);
                upload(localBitmap2);


            }

        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            // 从相机返回的数据
//            if (hasSdcard()) {
//                crop(Uri.fromFile(tempFile));
//            } else {
//                Toast.makeText(context, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
//            }

            if (hasSdcard()) {
                if (tempFile.exists()) {
                    Bitmap localBitmap1 = Imageutils.decodeFile(this.tempFile.getAbsolutePath());
                    int i = Imageutils.readPictureDegree(this.tempFile.getAbsolutePath());
                    L.e("角度 : " + i);
                    if (i != 0 && i != 270) {
                        localBitmap1 = Imageutils.rotateBitmap(localBitmap1, 90);
                    } else if (i == 270) {
                        localBitmap1 = Imageutils.rotateBitmap(localBitmap1, -90);
                    }
                    upload(localBitmap1);
                }

            } else {
                Toast.makeText(context, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }


        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {


                final Bitmap bitmap = data.getParcelableExtra("data");

            }


        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        super.onPause();
        UMengUtils.pagePause(8);
    }


    public void onSaveInstanceState(Bundle paramBundle) {
        if (tempFile != null)
            paramBundle.putString("tempFile", this.tempFile.getAbsolutePath());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        try {
//            // 将临时文件删除
//            tempFile.delete();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    private void initView() {
        toolBar.hideLine();
        toolBar.setBackgroundColor(getResources().getColor(R.color.transparent));
        toolBar.setLefeImage(getResources().getDrawable(R.drawable.white_back));

      /*  toolbar
        toolbar.hideLeftExp().hideRightImage().hideRightExp();
        toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });*/
    }

    private void init() {
        int statusBarColor = setTranslucentStatusColor();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        //使StatusBarTintView 和 actionbar的颜色保持一致，风格统一。
        tintManager.setStatusBarTintResource(statusBarColor == -1 ? R.color.colorPrimary : statusBarColor);
        tintManager.setStatusBarTintResource(R.color.statusBarColor);
//        // 设置状态栏的文字颜色
        tintManager.setStatusBarDarkMode(true, this);
    }

    public void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}
